package com.sakura.demo.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.JWSObject;
import com.sakura.demo.common.constant.AuthConstant;
import com.sakura.demo.common.model.UserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;

/**
 * @Author: zhengcan
 * @Date: 2022/5/17
 * @Description: 解析token信息
 * @Version: 1.0.0 创建
 */
@Slf4j
public class JwtTokenUtil {

    public static UserInfoDto parseTokenToUserInfo(String token) {
        if (ObjectUtils.isEmpty(token)) {
            return null;
        }
        String realToken = token.replace(AuthConstant.TOKEN_STANDARD_STYLE, "");
        UserInfoDto userInfoDto = null;
        try {
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            userInfoDto = JSONObject.parseObject(userStr, UserInfoDto.class);
        } catch (ParseException e) {
            log.error("[JwtTokenUtil]:解析token信息异常！token={}", realToken);
        }
        return userInfoDto;
    }

    public static String parseTokenToJsonStr(String token) {
        String userStr = "";
        if (ObjectUtils.isEmpty(token)) {
            return userStr;
        }
        String realToken = token.replace(AuthConstant.TOKEN_STANDARD_STYLE, "");
        try {
            JWSObject jwsObject = JWSObject.parse(realToken);
            userStr = jwsObject.getPayload().toString();
        } catch (ParseException e) {
            log.error("[JwtTokenUtil]:解析token信息异常！token={}", realToken);
        }
        return userStr;
    }
}
